﻿using DBMC_Core;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using System;
using System.Windows.Controls;
using AduSkin.Controls.Metro;
using AduSkin.Controls;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using Microsoft.Win32;
using System.Threading.Tasks;

namespace DBMC
{
    /// <summary>
    /// Tools.xaml 的交互逻辑
    /// </summary>
    public partial class Tools : Window
    {
        private bool isDragging;
        private Point startPoint;
        public ObservableCollection<AllSavePath> Saves { get; set; }
        Minecraft minecraft = new Minecraft();

        public Tools()
        {
            InitializeComponent();
            Load();
        }

        public async void Load()
        {
            LauncherCore.WriteLog($"启动器核心：工具 - 窗口打开正常");
            await Dispatcher.InvokeAsync(() =>
            {
                LauncherCore.WriteLog($"启动器核心：工具 - 获取游戏存档中...");
                List<AllSavePath> savePaths = LauncherTools.GetSavePaths(minecraft.SavesPath);
                if(savePaths.Count > 0)
                {
                    Saves = new ObservableCollection<AllSavePath>(savePaths);
                    IsSaves.ItemsSource = Saves;
                    SaveStats.Visibility = Visibility.Collapsed;
                    IsSaves.Visibility = Visibility.Visible;
                    LauncherCore.WriteLog($"启动器核心：工具 - 获取游戏存档成功");
                }
                else
                {
                    IsSaves.Visibility = Visibility.Hidden;
                    SaveStats.Visibility = Visibility.Visible;
                    LauncherCore.WriteLog($"启动器核心：工具 - 获取游戏存档失败，因为还未创建存档");
                }
            });
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            startPoint = e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPoint = e.GetPosition(this);
                this.Left += currentPoint.X - startPoint.X;
                this.Top += currentPoint.Y - startPoint.Y;
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Save_OpenFolder_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button.CommandParameter is AllSavePath allSavePath)
            {
                try
                {
                    LauncherCore.WriteLog($"启动器核心：工具 - 用户点击了“打开文件夹”，正在打开 {allSavePath.Name} 存档文件夹");
                    Process.Start("explorer.exe", allSavePath.Path);
                    LauncherCore.WriteLog($"启动器核心：工具 -  打开 {allSavePath.Name} 存档文件夹成功");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "工具",
                        Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：打开文件夹",
                        NotificationType = EnumPromptType.Success
                    });
                }
                catch (Exception)
                {
                    LauncherCore.WriteLog($"启动器核心：工具 -  打开 {allSavePath.Name} 存档文件夹失败");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "工具",
                        Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：打开文件夹",
                        NotificationType = EnumPromptType.Error
                    });
                }
            }
        }

        private void Save_Package_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button.CommandParameter is AllSavePath allSavePath)
            {
                LauncherCore.WriteLog($"启动器核心：工具 - 用户点击了“打包”，正在打包 {allSavePath.Name} 存档");
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "ZIP文件 (*.zip)|*.zip";
                saveFileDialog.Title = "打包成ZIP，请填写文件名称和选择保存位置";
                saveFileDialog.FileName = allSavePath.Name;

                if (saveFileDialog.ShowDialog() == true)
                {
                    string zipFilePath = saveFileDialog.FileName;

                    ZipFile.CreateFromDirectory(allSavePath.Path, zipFilePath);

                    LauncherCore.WriteLog($"启动器核心：工具 -  {allSavePath.Name} 存档打包成功，所在位置：{zipFilePath}");
                    MessageBoxResult messageBoxResult = AduMessageBox.Show($"要打开吗？", "打包成功", MessageBoxButton.YesNo);
                    if(messageBoxResult == MessageBoxResult.Yes)
                    {
                        Process.Start("explorer.exe", $"/select,\"{zipFilePath}\"");
                    }
                }
                else
                {
                    LauncherCore.WriteLog($"启动器核心：工具 -  用户取消打包 {allSavePath.Name} 存档");
                }
            }
        }

        private void Save_OpenToNBTExplorer_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button.CommandParameter is AllSavePath allSavePath)
            {
                LauncherCore.WriteLog($"启动器核心：工具 - 用户点击了“使用NBTExplorer打开”，正在唤起 NBTExplorer 打开 {allSavePath.Name} 存档");
                if (LauncherTools.NBTExplorer.Use(Path.Combine(allSavePath.Path, "level.dat")))
                {
                    LauncherCore.WriteLog($"启动器核心：工具 - 使用NBTExplorer打开 {allSavePath.Name} 存档成功");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "工具",
                        Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：使用NBTExplorer打开",
                        NotificationType = EnumPromptType.Success
                    });
                }
                else
                {
                    LauncherCore.WriteLog($"启动器核心：工具 - 使用NBTExplorer打开 {allSavePath.Name} 存档失败");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "工具",
                        Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：使用NBTExplorer打开",
                        NotificationType = EnumPromptType.Error
                    });
                }
            }
        }

        private void Save_FastSubmission_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button.CommandParameter is AllSavePath allSavePath)
            {
                LauncherCore.WriteLog($"启动器核心：工具 - 用户点击了“快捷投稿”，正在唤起 快捷投稿 窗口");
                SaveSubmission saveSubmission = new SaveSubmission(allSavePath.Name, allSavePath.Path);
                saveSubmission.ShowDialog();
            };
        }

        private void Save_Delete_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button.CommandParameter is AllSavePath allSavePath)
            {
                LauncherCore.WriteLog($"启动器核心：工具 - 删除 {allSavePath.Name} 存档");
                MessageBoxResult messageBoxResult = AduMessageBox.Show("确认要删除吗QAQ？", $"删除{allSavePath.Name}地图", MessageBoxButton.YesNo);
                if (messageBoxResult == MessageBoxResult.Yes)
                {
                    try
                    {
                        // 如果文件夹存在，则删除它
                        if (Directory.Exists(allSavePath.Path))
                        {
                            // 第二个参数为true表示删除文件夹内的所有子目录和文件
                            Directory.Delete(allSavePath.Path, true);
                            Load();
                            LauncherCore.WriteLog($"启动器核心：工具 - 删除 {allSavePath.Name} 存档成功");
                            NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                            {
                                Title = "工具",
                                Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：删除地图",
                                NotificationType = EnumPromptType.Success
                            });
                        }
                        else
                        {
                            LauncherCore.WriteLog($"启动器核心：工具 - 删除 {allSavePath.Name} 存档失败，因为存档不存在");
                            NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                            {
                                Title = "工具",
                                Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：删除地图",
                                NotificationType = EnumPromptType.Error
                            });
                        }
                    }
                    catch (IOException ex)
                    {
                        LauncherCore.WriteLog($"启动器核心：工具 - 删除 {allSavePath.Name} 存档失败，因为 {ex}");
                        NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                        {
                            Title = "工具",
                            Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：删除地图",
                            NotificationType = EnumPromptType.Error
                        });
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        LauncherCore.WriteLog($"启动器核心：工具 - 删除 {allSavePath.Name} 存档失败，因为 {ex}");
                        NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                        {
                            Title = "工具",
                            Content = $"类型：地图管理\n地图名：{allSavePath.Name}\n事件：删除地图",
                            NotificationType = EnumPromptType.Error
                        });
                    }
                }
            }
        }
    }
}
